package org.ling.xuan.pannel;

import cn.hutool.core.util.StrUtil;
import com.intellij.execution.impl.ConsoleViewImpl;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.openapi.project.Project;
import com.intellij.ui.components.JBTabbedPane;
import com.intellij.ui.components.JBTextArea;
import com.intellij.ui.table.JBTable;
import org.ling.xuan.compoment.CustomTableCellEditor;
import org.ling.xuan.config.SysConstant;
import org.ling.xuan.config.SystemProperties;
import org.ling.xuan.config.TestDbConfig;
import org.ling.xuan.util.ExUtil;
import org.ling.xuan.util.LxStrUtil;
import org.springframework.jdbc.core.RowMapper;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.ResultSetMetaData;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class SqlUtilPanel extends JPanel {
    private final JBTabbedPane tabbedPane;
    private final Project project;

    public SqlUtilPanel(Project project) {
        setSize(new Dimension(getWidth(),getHeight()));
        this.project = project;
        tabbedPane = new JBTabbedPane();
        tabbedPane.setSize(new Dimension(getWidth()-10,getHeight()-10));
        ConsoleView consoleView = new ConsoleViewImpl(project,false);
        consoleView.print("欢迎使用LxTool\n", ConsoleViewContentType.NORMAL_OUTPUT);
        tabbedPane.addTab("welcome",consoleView.getComponent());
        JBTextArea textArea = new JBTextArea(20,250);
        tabbedPane.addTab("-",new JScrollPane(textArea));
        add(tabbedPane);
    }

    public void executeBatch(String sqlStr){
        sqlStr=sqlStr.replace("\r\n","\n");
        String ss = StrUtil.split(sqlStr,"\n").stream().filter(StrUtil::isNotBlank).filter(s->!s.trim().startsWith("--")).collect(Collectors.joining(" "));
        if(StrUtil.isNotBlank(ss)){
            tabbedPane.removeAll();
            List<String> sss = StrUtil.split(ss,";");
            int i =1;
            for(String sql:sss){
                if(StrUtil.isNotBlank(sql)) {
                    execute(i++, sql);
                }
            }
        }else{
            tabbedPane.removeAll();
            ConsoleView consoleView = new ConsoleViewImpl(project,false);
            consoleView.print("no sql can be execute\n", ConsoleViewContentType.NORMAL_OUTPUT);
            tabbedPane.addTab("notice",consoleView.getComponent());
        }
        JBTextArea textArea = new JBTextArea(20,250);
        tabbedPane.addTab("-",new JScrollPane(textArea));
    }

    private void execute(int i, String sql) {
        try {
            String ex = SystemProperties.getOrDefaultStr(SysConstant.replaceSqlExecMap,"");
            Map<String,String> replaceMap = LxStrUtil.convertToMap(ex,";",":");
            for(String key:replaceMap.keySet()){
                sql = sql.replace(key,replaceMap.getOrDefault(key,""));
            }
            if (sql.trim().toLowerCase().startsWith("select")) {
                DefaultTableModel tableModel = new DefaultTableModel();
                TestDbConfig.getJdbcTemplate().query(sql, (RowMapper<Object>) (rs, rowNum) -> {
                    if (tableModel.getColumnCount() == 0) {
                        ResultSetMetaData metaData = rs.getMetaData();
                        int columnCount = metaData.getColumnCount();
                        for (int j = 1; j <= columnCount; j++) {
                            tableModel.addColumn(metaData.getColumnName(j));
                        }
                    }
                    Object[] rowData = new Object[tableModel.getColumnCount()];
                    for (int j = 1; j <= tableModel.getColumnCount(); j++) {
                        rowData[j - 1] = rs.getObject(j);
                    }
                    tableModel.addRow(rowData);
                    return 1;
                });
                if(tableModel.getColumnCount()>0) {
                    JPanel jbPanel = new JPanel(new BorderLayout());
                    JBTextArea textArea = new JBTextArea();
                    textArea.setText(sql);
                    jbPanel.add(new JScrollPane(textArea),BorderLayout.NORTH);
                    JBTable resultTable = new JBTable(tableModel);
                    resultTable.setDefaultEditor(Object.class,new CustomTableCellEditor());
                    jbPanel.add(new JScrollPane(resultTable),BorderLayout.CENTER);
                    tabbedPane.addTab("结果" + i, jbPanel);
                }else{
                    ConsoleView consoleView = new ConsoleViewImpl(project,false);
                    consoleView.print("sql执行成功:"+"\n"+"sql内容:"+sql+"\n"+"查询无结果", ConsoleViewContentType.NORMAL_OUTPUT);
                    tabbedPane.addTab("结果"+i,consoleView.getComponent());
                }
            } else {
                int row = TestDbConfig.getJdbcTemplate().update(sql);
                ConsoleView consoleView = new ConsoleViewImpl(project,false);
                consoleView.print("sql执行成功:"+"\n"+"sql内容:"+sql+"\n"+"影响行数:"+row, ConsoleViewContentType.NORMAL_OUTPUT);
                tabbedPane.addTab("结果"+i,consoleView.getComponent());
            }
        }catch (Exception e){
            String ss = ExUtil.getExMsg(e, "\n");
            ss = e.getMessage()+"\n"+ss;
            ConsoleView consoleView = new ConsoleViewImpl(project,false);
            consoleView.print("sql执行失败:"+"\n"+"sql内容:"+sql+"\n"+ss, ConsoleViewContentType.NORMAL_OUTPUT);
            tabbedPane.addTab("结果"+i,consoleView.getComponent());
        }
    }
}
